package com.github.xaidanwang.data.upload.download.controller;

import com.github.xaidanwang.data.upload.download.biz.AccountBiz;
import com.github.xaidanwang.data.upload.download.cache.RedisDao;
import com.github.xaidanwang.data.upload.download.dao.AccountDoMapper;
import com.github.xaidanwang.data.upload.download.dto.Task;
import com.github.xaidanwang.data.upload.download.entity.AccountDo;
import com.github.xaidanwang.data.upload.download.vo.TaskVo;
import com.github.xaidanwang.exception.valid.ParamException;
import com.github.xaidanwang.response.CommonResult;
import com.github.xaidanwang.response.ConstantEnum;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;


/**
 * @author wang yi fei
 * @date 2020/1/7 11:47
 */
@RestController
@RequestMapping("read")
@Slf4j
public class ReadBackController {
	public static final int ROOMID_LENGTH = 19;
	@Autowired
	private AccountBiz accountBiz;
	@Autowired
	private RedisDao redisDao;
	@ApiOperation(value = "上传任务")
	@GetMapping(value = "/uploadTask")
	public CommonResult uploadTask(Task task){
		if (task.getDatTime() > 300){
			return CommonResult.buildWithData(ConstantEnum.GLOBAL_SUCCESS,"上传失败,时间不对!");
		}
		log.info("添加任务task:{}",task);
		if (StringUtils.isEmpty(task.getRoomeNum()) || task.getRoomeNum().equals("undefined")){
			return CommonResult.buildWithData(ConstantEnum.GLOBAL_SUCCESS,"上传失败,房间号格式不正确!");
		}
		if (task.getRedNum() == -1){
			redisDao.addStopLiveBroadcastRoomId(task.getRoomeNum());
		}else {
			redisDao.addLiveBroadcastTask(task);
		}
		return CommonResult.buildWithData(ConstantEnum.GLOBAL_SUCCESS,"上传成功!");
	}

	@PostMapping(value = "/uploadTask")
	public CommonResult batchUploadTask(@RequestBody List<Task> taskList){
		if (taskList == null){
			return CommonResult.buildWithData(ConstantEnum.GLOBAL_SUCCESS,"上传成功!");
		}
		for (Task task : taskList){
			uploadTask(task);
		}
		return CommonResult.buildWithData(ConstantEnum.GLOBAL_SUCCESS,"上传成功!");
	}

	@ApiOperation(value = "获取任务")
	@GetMapping(value = "/getTask")
	public CommonResult getTask(@RequestParam(value = "username", defaultValue = "123") String username,
	                            @RequestParam(value = "password", defaultValue = "123") String password,
	                            @RequestParam(value = "second",required = false,defaultValue = "15") int second,
	                            @RequestParam(value = "startBoubi",required = false,defaultValue = "15") int startBoubi,
	                            @RequestParam(value = "endBoubi",required = false,defaultValue = "9999999") int endBoubi,
	                            @RequestParam(value = "offset",required = false,defaultValue = "3") int offset){
		long nowSecond = System.currentTimeMillis()/1000;
		AccountDo accountDo = accountBiz.getAccountDoByUserName(username);
		if (accountDo == null || !accountDo.getPassword().equals(password)){
			throw new ParamException("账号密码不匹配");
		}
		Set<String> roomeSet = redisDao.getLiveBroadcastTask(nowSecond + offset,nowSecond + second);

//		String roomId2 = getBigRedEnvelopeAlgorithm(roomeSet);
//		if (StringUtils.isNotEmpty(roomId2)){
//			Double time = redisDao.getRoomIdTime(roomId2);
//			TaskVo taskVo = new TaskVo();
//			taskVo.setRoomId(roomId2.substring(0,ROOMID_LENGTH));
//			taskVo.setTime(time - nowSecond);
//			Integer doubi = redisDao.getRoomDoubi(roomId2);
//			Integer count = redisDao.getRoomHaveGetCount(roomId2);
//			log.info("{}获取{}抖币的直播间成功{},{},{}",username,doubi,roomId2,time - nowSecond,count);
//			return CommonResult.buildWithData(ConstantEnum.GLOBAL_SUCCESS,taskVo);
//		}

		if (roomeSet != null && roomeSet.size() > 0){
			for (String roomId:roomeSet){
				Integer doubi = redisDao.getRoomDoubi(roomId);
				if (doubi < startBoubi || doubi > endBoubi){
					continue;
				}
				Integer count = redisDao.getRoomHaveGetCount(roomId);
				if (doubi < 22 && count > 10){
					continue;
				}
//				if (doubi < 210 && count > 30){
//					continue;
//				}
//				if (doubi < 520 && count > 50){
//					continue;
//				}
//				if (doubi < 2010 && count > 100){
//					continue;
//				}
				if (count == 4){
					redisDao.addRoomIdlibListAgain(roomId,nowSecond);
				}
				Double time = redisDao.getRoomIdTime(roomId);
				TaskVo taskVo = new TaskVo();
				taskVo.setRoomId(roomId.substring(0,ROOMID_LENGTH));
				taskVo.setTime(time - nowSecond);
				log.info("{}获取{}抖币的直播间成功{},{},{}",username,doubi,roomId.substring(0,ROOMID_LENGTH),time - nowSecond,count);
				return CommonResult.buildWithData(ConstantEnum.GLOBAL_SUCCESS,taskVo);
			}
		}
		Integer num = redisDao.getLiveBroadcastTaskCount();
		return CommonResult.buildWithData(ConstantEnum.GLOBAL_SUCCESS,num);
	}

	/**
	 * true 表示返回，不返回本次任务，false 表示 可以返回该任务
	 * @param roomId
	 * @param limit
	 * @param startBoubi
	 * @return true 该任务不返回，false 返回该任务
	 */
	private boolean limitPhoneNumber(String roomId,Integer limit,Integer startBoubi){
		Integer doubi = redisDao.getRoomDoubi(roomId);
		if (doubi < startBoubi){
			return true;
		}
		if (doubi > 22){
			log.info("获取抖币大于21直播间成功{}",roomId);
			return false;
		}
		Integer count = redisDao.getRoomHaveGetCount(roomId);
		if (count > limit){
			return true;
		}
		log.info("获取直播间成功{},{}",roomId,count);
		return false;
	}

	private String getBigRedEnvelopeAlgorithm(Set<String> roomeSet){
		for (String roomId: roomeSet){
			Integer doubi = redisDao.getRoomDoubi(roomId);
			if (doubi > 25){
				return roomId;
			}
		}
		return null;
	}

	public static void main(String[] args) {
		System.out.println(System.currentTimeMillis()/1000);
	}

}
